package controller.member;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.datastore.Email;

import model.enumeration.MemberState;
import model.jdo.Member;
import model.mail.MailHelper;
import model.persistence.PMF;

public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = -2731436861079703444L;

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PersistenceManager pm = null;
		Query q = null;
		
        try {
        	req.setCharacterEncoding("utf-8");
    		String email = req.getParameter("email");
        	List<Member> results;
        	
        	pm = PMF.get().getPersistenceManager();
        	q = pm.newQuery(Member.class);
        	q.setFilter("email == emailParam");
        	q.declareParameters("Object emailParam");
        	results = (List<Member>) q.execute(new Email(email));
        	if (results.isEmpty()) {
        		String password = req.getParameter("pass");
        		String nickname = req.getParameter("nickName");
        		Member member = new Member(null, new Email(email), password, nickname,
        				MemberState.WAIT_FOR_CONFIRM.ordinal());
    			long id;
    			HttpSession session = req.getSession();
    			String subject = nickname + "先生/小姐您好，再次感謝您註冊成為課程評論社群的會員"
			    		+ "，此為電子信箱認證信，點選認證連結後即可啟用帳號";
    			String msgBody;
        		
        		id = pm.makePersistent(member).getKey().getId();
    			msgBody = nickname + "先生/小姐您好:\n\n再次感謝您註冊成為此社群的會員\n\n以下為認證連結:\n\n"
            			+ "http://coucomm.appspot.com/confirmMember?key=" + id
            			+ "\n\n請點選認證連結即可完成認證並且立刻開始使用此社群!\n\n課程評論社群管理員";
        		session.setAttribute("id", String.valueOf(id));
                session.setAttribute("email", email);
                session.setAttribute("nickname", nickname);
                MailHelper.send("a0838809919@gmail.com", "課程評論社群管理員", email, nickname + "先生/小姐",
                		subject, msgBody);
        	}
        	else {
        		resp.setCharacterEncoding("utf-8");
        		resp.getWriter().print("emailHasBeenUsed");
        	}
        } finally {
        	q.closeAll();
            pm.close();
        }
	}
}
